//
//  YBXueYaInputController.m
//  孕妙
//
//  Created by Raoy on 16/4/11.
//  Copyright © 2016年 是源科技. All rights reserved.
//

#import "YBXueYaInputController.h"
#import "YBSelectPickerWindow.h"
#import <CoreBluetooth/CoreBluetooth.h>

@interface YBXueYaInputController ()<UIPickerViewDelegate, UIPickerViewDataSource, CBCentralManagerDelegate, CBPeripheralDelegate>
//弹出手动输入窗口
@property (strong, nonatomic) YBSelectPickerWindow *pickerWindow;
@property(nonatomic, strong)CBCentralManager *mgr;
@property(nonatomic, strong)NSMutableArray   *peripherals;
//当前外设
@property(nonatomic, strong)CBPeripheral  *peripheral;

//当前外设的服务和特征
@property(nonatomic, strong)CBCharacteristic    *dataInteractCharacteristic;

/**
 * 是否收到血压计开始指令
 */
@property (nonatomic, getter=isGetStartMeasure) BOOL getStartMeasure;
/**
 * 测量错误弹框
 */
@property (nonatomic, strong) UIAlertView *measureErrorAlertView;

@end

@implementation YBXueYaInputController
{
    NSString *selectIntStrH;  // 高血压
    NSString *selectIntStrL; //低血压
    
    NSMutableArray *intArrayH; //选择器 高血压部分
    NSMutableArray *intArrayL; //选择器 低血压部分
    NSString *valueStr;
}
- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = @"记录血压";
    self.view.backgroundColor =  SYColor(245, 245, 245);;
//    self.navigationItem.leftBarButtonItem = [UIBarButtonItem itemWithIcon:@"YB_backToSupper"  highIcon:nil target:self action:@selector(clickLeftButtonToSupper2:)];
    self.navigationItem.rightBarButtonItem =  [[UIBarButtonItem alloc] initWithCustomView:self.rightBtn];
    
    [self.rightBtn addTarget:self action:@selector(xueyarigheBtnClick:) forControlEvents:UIControlEventTouchUpInside];
    [self scanBle];
    //开始使用蓝牙设备测量
    [self.startbtn2 addTarget:self action:@selector(openBle:) forControlEvents:UIControlEventTouchUpInside];
    
    // 高血压范围
    intArrayH = [NSMutableArray array];
    for (int index = 40; index < 200; index++) {
        NSString *str = [NSString stringWithFormat:@"%d", index];
        [intArrayH addObject:str];
    }
    
    //低血压范围
    intArrayL = [NSMutableArray array];
    for (int index = 40; index < 140; index++) {
        NSString *str = [NSString stringWithFormat:@"%d", index];
        [intArrayL addObject:str];
    }
    self.measureErrorAlertView = [[UIAlertView alloc] initWithTitle:@"测量出错" message:@"测量错误，是否重新测试" delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"重新测试", nil];
    
    //设置日期栏
    [self setTitle:@"请输入收缩压:\n请输入舒张压:" buyTitle:@"购买血压计" indexImage:2];
    //设置血压
    valueStr = @" mmHg \n mmHg";
    [self createLabel:valueStr];
    // Do any additional setup after loading the view.
}

- (void)clickLeftButtonToSupper2:(id)sender
{
    self.pickerWindow = nil;  //释放内存
    [self.navigationController popViewControllerAnimated:YES];
}

- (void)xueyarigheBtnClick:(id)sender
{
    self.fuGaiView.hidden = NO;
    if (_pickerWindow == nil) {
        _pickerWindow = [[YBSelectPickerWindow alloc] init];
        [_pickerWindow setInterFace:@"血压(mmHg)"];
        _pickerWindow.selectPickerView.delegate = self;
        _pickerWindow.selectPickerView.dataSource = self;
    }else{
        
        _pickerWindow.hidden = NO;
    }
    [_pickerWindow.selectPickerView selectRow:50  inComponent:0 animated:YES];
    [_pickerWindow.selectPickerView selectRow:35 inComponent:1 animated:YES];
    selectIntStrH = intArrayH[50];
    selectIntStrL = intArrayL[35];
    [_pickerWindow.sureBtn addTarget:self action:@selector(saveDataBtn) forControlEvents:UIControlEventTouchUpInside];
    [_pickerWindow.cancelBtn addTarget:self action:@selector(cancelBtnClicked:) forControlEvents:UIControlEventTouchUpInside];
}

- (void)saveDataBtn
{
    valueStr = nil;
    self.fuGaiView.hidden = YES;
    _pickerWindow.hidden = YES;
    valueStr = [NSString stringWithFormat:@"%@mmHg \n%@ mmHg", selectIntStrH, selectIntStrL];
    [self createLabel:valueStr];
    [self.view setNeedsDisplay];
    
    [self getUserParmaterData:[NSString stringWithFormat:@"%@", selectIntStrH] selectionValue:2 gaoxueya:[NSString stringWithFormat:@"%@", selectIntStrL]];
}
- (void)cancelBtnClicked:(id)sender
{
    self.fuGaiView.hidden = YES;
}

- (void)viewDidAppear:(BOOL)animated
{
    NSLog(@"sfeawrr------");
    [super viewDidAppear:YES];
}

- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:YES];
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)openBle:(UIButton *)button
{
    [self scanBle];
    
}

#pragma mark- 连接蓝牙外设


- (NSMutableArray *)peripherals
{
    if (!_peripherals)
    {
        _peripherals = [NSMutableArray array];
    }
    
    return _peripherals;
}

- (CBCentralManager *)mgr
{
    if (!_mgr){
        
        self.mgr = [[CBCentralManager alloc] initWithDelegate:self queue:nil];
    }
    
    return _mgr;
}

- (void)scanBle
{
    if (self.useAddviceWindow.hidden == NO && self.useAddviceWindow != nil) {
        [self.mgr stopScan];
        self.peripheral = nil;
        self.mgr = nil;
        return;
    }
    self.startbtn2.isAccessibilityElement = NO;
    [MBProgressHUD showMessage:@"正在搜索设备......"];
    [self.mgr stopScan];
    [self.mgr scanForPeripheralsWithServices:nil options:nil];
    self.startbtn2.isAccessibilityElement = YES;
}



#pragma mark - UIPickerView
- (NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView
{
    return 2;
}

- (NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component
{
    if (component == 0) {
        return intArrayH.count;
    } else {
        return intArrayL.count;
    }
}

- (NSString *)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component
{
    if (component == 0) {
        return intArrayH[row];
    }else{
    
        return intArrayL[row];
    }
}


- (void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component
{
    if (component == 0) {
        selectIntStrH = intArrayH[row];
    } else {
        selectIntStrL = intArrayL[row];
    }
    
}





#pragma mark - CBCentralManagerDelegate

//检查设备是否支持BLE
-(void)centralManagerDidUpdateState:(CBCentralManager *)central
{
    switch (central.state) {
        case CBCentralManagerStatePoweredOn:// 蓝牙打开
            NSLog(@"CBCentralManagerStatePoweredOn");
            [self.mgr scanForPeripheralsWithServices:nil options:nil];
            break;
        case CBCentralManagerStatePoweredOff://蓝牙关闭
            self.peripheral = nil;
            break;
        case CBCentralManagerStateUnsupported:
            NSLog(@"State Unsupported");
            break;
            
        default:
            NSLog(@"Central Manager Did Update State");
            break;
    }
}

/**
 *  发现外围设备的时候调用
 */
- (void)centralManager:(CBCentralManager *)central didDiscoverPeripheral:(CBPeripheral *)peripheral advertisementData:(NSDictionary *)advertisementData RSSI:(NSNumber *)RSSI
{
    [MBProgressHUD hideHUD];
    NSLog(@"didDiscoverPeripheralName :%@", peripheral.name);
    
    // 添加外围设备
    if (![self.peripherals containsObject:peripheral] && [peripheral.name hasPrefix:@"Bluetooth"] && [peripheral.name hasSuffix:@"BP"]) {
        // 设置外设的代理
        peripheral.delegate = self;
        [self.peripherals addObject:peripheral];
    } else {
        return;
    }
    
    for (CBPeripheral *per in self.peripherals) {
        if (per.state == NO) {
            self.peripheral = peripheral;
            [self.mgr connectPeripheral:self.peripheral options:nil];
        }
    }
}


/**
 *  连接到某个外设的时候调用
 */
- (void)centralManager:(CBCentralManager *)central didConnectPeripheral:(CBPeripheral *)peripheral
{
    NSLog(@"didConnectPeripheral");
    [self.mgr stopScan];
    // 查找外设中的所有服务
    //#warning 通过传入一个存放服务UDID的数组进去，过滤掉一些不要的服务
    [peripheral discoverServices:nil];
    
    
    
}

//连接外设失败
-(void)centralManager:(CBCentralManager *)central didFailToConnectPeripheral:(CBPeripheral *)peripheral error:(NSError *)error
{
    NSLog(@"************连接外设失败*************");
    // 扫描
    [self.mgr scanForPeripheralsWithServices:nil options:nil];
    [self.peripherals removeAllObjects];
}

/**
 *  跟某个外设失去连接
 */
- (void)centralManager:(CBCentralManager *)central didDisconnectPeripheral:(CBPeripheral *)peripheral error:(NSError *)error
{
    //    NSLog(@"didDisconnectPeripheral:%@", peripheral.name);
    self.peripheral = nil;
    [self.peripherals removeAllObjects];
    self.dataInteractCharacteristic = nil;
    self.getStartMeasure = NO;
    // 扫描
    [self.mgr scanForPeripheralsWithServices:nil options:nil];
    [self.peripherals removeAllObjects];
    NSLog(@"蓝牙断开didDisconnectPeripheral");
}

#pragma mark - CBPeripheralDelegate
/**
 *  外设已经查找到服务
 */
- (void)peripheral:(CBPeripheral *)peripheral didDiscoverServices:(NSError *)error
{
    if (self.useAddviceWindow.hidden == NO && self.useAddviceWindow != nil) {
        [self.mgr stopScan];
        self.peripheral = nil;
        self.mgr = nil;
        return;
    }
    NSLog(@"didDiscoverServices:%@", peripheral.services);
    [self.buletoothImageView setImage:[UIImage imageNamed:@"蓝牙连接"]];
    // 遍历所有的服务
    for (CBService *service in peripheral.services) {
        // 过滤掉不想要的服务
        if ([service.UUID isEqual:[CBUUID UUIDWithString:@"0xFFF0"]]) {
            // 找到想要的服务"@"0xFFF0""
            
            // 扫描服务下面的特征
            //#warning 通过传入一个存放特征UDID的数组进去，过滤掉一些不要的特征
            [peripheral discoverCharacteristics:nil forService:service];
        }
    }
}


- (void)peripheral:(CBPeripheral *)peripheral didDiscoverCharacteristicsForService:(CBService *)service error:(NSError *)error
{
    NSLog(@"didDiscoverCharacteristicsForService:%@", service.characteristics);
    
    [self.peripherals removeAllObjects];
    // 遍历所有的特征
    for (CBCharacteristic *characteristic in service.characteristics) {
        
        // 过滤掉不想要的特征
        if ([characteristic.UUID isEqual:[CBUUID UUIDWithString:@"0xFFF1"]]) { //FFF8FFF2-FFF1-FFF4-FFF0-28011800FFC0
            // 找到想要的特征
            NSLog(@"----------------------找到读写特征");
            [peripheral setNotifyValue:YES forCharacteristic:characteristic];
        }
        if ([characteristic.UUID isEqual:[CBUUID UUIDWithString:@"0xFFF2"]]) {
            NSLog(@"----------------------找到写特征");
            self.dataInteractCharacteristic = characteristic;
            for (int index = 0; index < 5; index++) {
                if (!self.isGetStartMeasure) {
                    NSLog(@"index = %d", index);
                    [self requestDataToBlueLinkSingle:characteristic];
                }
            }
        }
    }
}

// 获取外设发来的数据，不论是read和notify,获取数据都是从这个方法中读取。
- (void)peripheral:(CBPeripheral *)peripheral didUpdateValueForCharacteristic:(CBCharacteristic *)characteristic error:(NSError *)error
{
    
    if (error)
    {
        NSLog(@"didUpdateValueForCharacteristicError: %@", error.localizedDescription);
        return;
    }
    
    if([characteristic.UUID isEqual:[CBUUID UUIDWithString:@"0xFFF1"]])
    {
#pragma mark 接收处理数据
        NSLog(@"接收数据: %@",characteristic.value);
        // 接收到蓝牙数据 先分析 再回传给代理 最后发送指令关机
        [self analyseData:characteristic.value withPeripheral:peripheral];
    }
}


// 接收到蓝牙数据 先分析
- (void)analyseData:(NSData *)data withPeripheral:(CBPeripheral *)aPer
{
    
    Byte *bytes = (Byte *)[data bytes];
    
    switch (bytes[2]) {
        case 0x06: // 正在测量
        {
            self.getStartMeasure = YES;
            [MBProgressHUD showSuccess:@"正在测量，请稍候1－2分钟..."];
            break;
        }
        case 0xFB: // 测量的中间数据
            break;
        case 0xFC: // 测量结果
            [MBProgressHUD hideHUD];
            // [0xFD,0xFD,0xFC, SYS,DIA,PUL, 0X0D, 0x0A]	;测试结果
            int SYSValue = bytes[3];  // 高压
            int DIAValue = bytes[4];  // 低压
//            int PULValue = bytes[5];  // 脉搏
//            selectIntStrH = [NSString stringWithFormat:@"%d", SYSValue];
//            selectIntStrL = [NSString stringWithFormat:@"%d", DIAValue];
            valueStr = [NSString stringWithFormat:@"%d mmHg \n%dmmHg", SYSValue, DIAValue];
            [self createLabel:valueStr];
            [self.view setNeedsDisplay];
            [self getUserParmaterData:[NSString stringWithFormat:@"%d", SYSValue] selectionValue:2 gaoxueya:[NSString stringWithFormat:@"%d", DIAValue]];
//            valueStr = @"0 mmHg \n0 mmHg";
            
//            self.PULF.text = [NSString stringWithFormat:@"%d", self.PULValue];
            break;
        case 0xFD: // 血压计异常（多种异常情况）
            [MBProgressHUD hideHUD];
            
            if ((bytes[3] == 0x0E && bytes[4] == 0x0D && bytes[5] == 0x0A)|| (bytes[3] == 0x01 && bytes[4] == 0x0D && bytes[5] == 0x0A) || (bytes[3] == 0x02 && bytes[4] == 0x0D && bytes[5] == 0x0A) || (bytes[3] == 0x03 && bytes[4] == 0x0D && bytes[5] == 0x0A) || (bytes[3] == 0x05 && bytes[4] == 0x0D && bytes[5] == 0x0A) || (bytes[3] == 0x0C && bytes[4] == 0x0D && bytes[5] == 0x0A)) {
                [self.measureErrorAlertView show];
            } else if (bytes[3] == 0x0B  && bytes[4] == 0x0D && bytes[5] == 0x0A) {
                [MBProgressHUD showError:@"血压计电池电量过低"];
            }
            break;
        case 0x07: // 关机了
            [MBProgressHUD showSuccess:@"血压计终于可以休息了!!"];
            break;
            
        default:
            break;
    }
}
/**
 *  蓝牙连接信号
 */
-(void)requestDataToBlueLinkSingle:(CBCharacteristic *)achar
{//[0xFD,0xFD,0xFA,0x05,0X0D, 0x0A]
    Byte bytes[6];
    bytes[0] = 0xFD;
    bytes[1] = 0xFD;
    bytes[2] = 0xFA;
    bytes[3] = 0x05;
    bytes[4] = 0X0D;
    bytes[5] = 0x0A;
    NSData *dataa = [[NSData alloc] initWithBytes:bytes length:6];
    
    [self.peripheral writeValue:dataa forCharacteristic:achar type:CBCharacteristicWriteWithResponse];
}

/**
 *  关机信号
 */
-(void)requestDataToBluePowoffBPM:(CBCharacteristic *)achar
{//[0xFD,0xFD,0xFE, 0x06, 0X0D, 0x0A]
    Byte bytes[6];
    bytes[0] = 0xFD;
    bytes[1] = 0xFD;
    bytes[2] = 0xFE;
    bytes[3] = 0x06;
    bytes[4] = 0X0D;
    bytes[5] = 0x0A;
    NSData *dataa = [[NSData alloc] initWithBytes:bytes length:6];
    
    [self.peripheral writeValue:dataa forCharacteristic:achar type:CBCharacteristicWriteWithResponse];
}

#pragma mark -UIAlertView代理方法
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    if ([self.measureErrorAlertView isEqual:alertView]) {
        if (buttonIndex == 1) {
            // 重新测量
            if (self.peripheral && self.peripheral.state == CBPeripheralStateConnected) {
                [self requestDataToBlueLinkSingle:self.dataInteractCharacteristic];
            } else {
                [MBProgressHUD showError:@"亲，您的血压计处于失联状态!!"];
                [self.mgr stopScan];
            }
        }
    }
}
//- (IBAction)measureOne:(id)sender {
//    // 重新测量
//    if (self.peripheral && self.peripheral.state == CBPeripheralStateConnected) {
//        [self requestDataToBlueLinkSingle:self.dataInteractCharacteristic];
//    } else {
//        [MBProgressHUD showError:@"亲，您的血压计处于失联状态!!"];
//    }
//}
//
//- (IBAction)powOffBPM:(id)sender {
//    // 重新测量
//    if (self.peripheral && self.peripheral.state == CBPeripheralStateConnected) {
//        [self requestDataToBluePowoffBPM:self.dataInteractCharacteristic];
//    } else {
//        [MBProgressHUD showError:@"亲，您的血压计处于失联状态!!"];
//    }
//}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
